import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CategoryEntity } from './category.entity';
import { CategoryDto } from './category.dto';
import { CommonStatus } from '~/common/entity/common.entity';
import { CategoryWithSymptoms } from './category.types';
import { CategoryDiseaseService } from '../category-disease/category-disease.service';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly categoryRepository: Repository<CategoryEntity>,
    private readonly categoryDiseaseService: CategoryDiseaseService
  ) {}

  private generateCode(): string {
    // 使用时间戳加随机数生成唯一code
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000)
      .toString()
      .padStart(3, '0');
    return `CAT${timestamp}${random}`;
  }

  /**
   * 创建分类
   */
  async create(dto: CategoryDto): Promise<CategoryEntity> {
    const category = new CategoryEntity();
    Object.assign(category, dto);

    // 自动生成code
    category.code = this.generateCode();

    // 设置默认值
    if (category.isActive === undefined) {
      category.isActive = CommonStatus.YES;
    }
    if (category.isDeleted === undefined) {
      category.isDeleted = CommonStatus.NO;
    }
    category.sortOrder = 0; // 设置默认排序值为0

    return await this.categoryRepository.save(category);
  }

  /**
   * 查询所有分类
   */
  async findAll(): Promise<CategoryEntity[]> {
    return await this.categoryRepository.find({
      select: ['id', 'name', 'code', 'description'],
      where: {
        isDeleted: CommonStatus.NO,
        isActive: CommonStatus.YES,
      },
      order: {
        sortOrder: 'ASC',
      },
    });
  }

	/**
   * 按名称和编码模糊查询分类
   * @param name 分类名称（模糊匹配）
   * @param code 分类编码（模糊匹配）
   */
  async searchByNameAndCode(name?: string, code?: string): Promise<CategoryEntity[]> {
    // 使用 queryBuilder 构建模糊查询
    const queryBuilder = this.categoryRepository.createQueryBuilder('category')
      .select(['category.id', 'category.name', 'category.code', 'category.description', 'category.isActive'])
      .where('category.isDeleted = :isDeleted', { isDeleted: CommonStatus.NO })

    // 添加模糊查询条件
    if (name) {
      queryBuilder.andWhere('category.name LIKE :name', { name: `%${name}%` });
    }

    if (code) {
      queryBuilder.andWhere('category.code LIKE :code', { code: `%${code}%` });
    }

    // 排序
    queryBuilder.orderBy('category.sortOrder', 'ASC');

    return queryBuilder.getMany();
  }

  /**
   * 查询分类 - 根据用户信息，是否有症状
   * @param userId 用户ID
   * @param name 可选的分类名称（模糊匹配）
   * @param code 可选的分类编码（模糊匹配）
   */
  async findAllByUser(userId?: number, name?: string, code?: string): Promise<CategoryWithSymptoms[]> {
    const categories: CategoryWithSymptoms[] = name || code
      ? await this.searchByNameAndCode(name, code)
      : await this.findAll();

    if (!userId) {
      return categories.map((category) => {
        category.hasSymptoms = false; // 用户未登录，所有分类没有症状
        return category;
      });
    }

    // 查询用户关联的病症分类ID列表
    const userDiseaseIds = await this.categoryDiseaseService.findDiseaseIdsByUserId(userId);

    // 遍历所有分类，检查用户是否有对应的病症
    return categories.map((category) => {
      // 如果用户的病症ID列表中包含当前分类ID，则设置hasSymptoms为true
      category.hasSymptoms = userDiseaseIds.includes(category.id);
      return category;
    });
  }

  /**
   * 更新分类信息
   * @param id 分类ID
   * @param dto 更新的分类数据
   */
  async update(id: number, dto: Partial<CategoryDto>): Promise<CategoryEntity> {
    // 查询分类是否存在
    const category = await this.categoryRepository.findOne({
      where: { id, isDeleted: CommonStatus.NO }
    });

    // 如果分类不存在，抛出异常
    if (!category) {
      throw new BadRequestException(`分类ID为${id}的记录不存在`);
    }

    // 更新分类信息
    if (dto.name !== undefined) {
      category.name = dto.name;
    }
    if (dto.description !== undefined) {
      category.description = dto.description;
    }
    if (dto.isActive !== undefined) {
      category.isActive = dto.isActive;
    }

    // 保存更新
    return await this.categoryRepository.save(category);
  }

  /**
   * 软删除分类
   * @param id 分类ID
   */
  async softDelete(id: number): Promise<CategoryEntity> {
    // 查询分类是否存在
    const category = await this.categoryRepository.findOne({
      where: { id, isDeleted: CommonStatus.NO }
    });

    // 如果分类不存在，抛出异常
    if (!category) {
      throw new BadRequestException(`分类ID为${id}的记录不存在`);
    }

    // 设置为已删除状态
    category.isDeleted = CommonStatus.YES;

    // 保存更新
    return await this.categoryRepository.save(category);
  }
}
